<template>
  <div class="inner">
    <div class="left">
      <ul class="tree">
        <li v-for="(val, key) in roleList" :key="key" :class="{ active: val === isActive }" class="liStyle"
          @click="selRoleFn(key)">
          <span>{{ val }}</span>
        </li>
      </ul>
    </div>
    <div class="right">
      <div class="searchBox">
        <el-form class="demo-form-inline" label-position="right" label-width="80px" @submit.native.prevent>
          <div class="serFlexBox">
            <div class="inputBox">
              <el-row :gutter="20">
                <el-col :span="10">
                  <el-form-item label="姓名">
                    <el-input v-clearEmoji v-model.trim="name" style="width: 100%" clearable @keyup.enter.native="searchFn" placeholder="请输入..."/>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div class="btnBox">
              <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
              <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
            </div>
          </div>
        </el-form>
      </div>
      <el-button class="addBtn" style="width:82px;" @click="addUserFn" v-has="'builtInRole_addUSer'">关联用户</el-button>
      <div class="bottomTable" id="tableBox"  v-height>
        <div class="table" style="flex:1;">
          <vxe-table :column-config="{resizable: true}" border class="tablebox" ref="xTable1" :row-config="{isHover: true}" :scroll-y="{ enabled: true,gt:21 }" style="width: 100%" height="100%" size="medium" align="center">
            <vxe-column type="seq" width="80" title="序号" />
            <vxe-column field="userName" title="用户名" :min-width="elTableAdaptationWidth('userName', userList)"/>
            <vxe-column field="employeeName" title="姓名" :min-width="elTableAdaptationWidth('empoyeeName', userList)"/>
            <vxe-column field="deptName" title="所属部门" min-width="200"/>
            <vxe-column title="更新时间" min-width="150">
              <template v-slot="{ row }">
                {{ row.updateTime | parseTime }}
              </template>
            </vxe-column>
            <vxe-column v-if="$showFn(['builtInRole_del'])" title="操作">
              <template v-slot="{ row }">
                <el-button type="text" style="margin-right: 10px; color: red"
                  @click="$delFn('内置角色', del, row)" v-has="'builtInRole_del'">删除</el-button>
                <!-- <template>
                  <el-popconfirm
                    title="确定要删除该部门吗？"
                    @onConfirm="del(row)"
                  >
                    <el-button slot="reference" style="color:red;margin-left: 10px;" type="text">删除</el-button>
                  </el-popconfirm>
                </template> -->
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <div style="padding-top: 20px; height: 50px;">
          <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
            layout="total, ->,sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
    <!-- 新增/修改弹窗 -->
    <el-dialog :close-on-click-modal="false" :title="dTitle" width="30%" :visible.sync="dialogFormVisible"
      @close="btnClose">
      <el-form ref="addForm" :model="roleFormData" :rules="addRules" label-width="90px">
        <el-form-item label="内置角色:" >
          {{ isActive }}
        </el-form-item>
        <el-form-item label="所属部门:" prop="deptId">
          <el-select v-model="roleFormData.deptId" clearable popper-class="eloption" filterable
            @change="selDept">
            <el-option v-for="item in deptList" :key="item.id" :value="item.id" :label="item.deptName" />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名:" prop="name">
          <el-select v-model="roleFormData.name" clearable popper-class="eloption" filterable>
            <el-option v-for="item in nameList" :key="item.id" :value="item.id" :label="item.employeeName" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button class="celBtn" @click="btnClose">取 消</el-button>
        <el-button class="addBtn" @click="btnOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDictValueAndNameSource } from "@/api/dictionary";
import {
  getDeptListEasy,
  selectSysUserByDept,
  bindRoleUser,
  selectInternalRoleUser,
  deleteInternalRoleUser,
} from "@/api/system";
export default {
  name: "BuiltInRole",
  data() {
    return {
      roleList: [],
      isActive: "",
      name: "",
      isSearch: false,
      userList: [],
      deptList: [],
      deptId: "",
      code: "0",
      nameList: [],
      // nameId: '',
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      dialogFormVisible: false,
      roleFormData: {
        deptId: "",
        name: "",
      },
      addRules: {
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请选择用户",
            trigger: "blur",
          },
        ],
      },
      dTitle: "关联用户",
    };
  },
  watch: {
    roleList: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal.length > 0) {
          console.log(newVal["0"]);
          console.log(newVal, "0000");
          console.log(0);
          this.isActive = newVal["0"];
          // this.code = '0'
          // console.log(this.code)
        }
      },
    },
  },
  created() {
    this.getRoleList();
    this.getDeptListEasy();
    this.selectInternalRoleUser();
  },
  methods: {
    selRoleFn(key) {
      console.log(key);
      this.code = key;
      this.isActive = this.roleList[key];
      this.selectInternalRoleUser();
    },
    async selectInternalRoleUser() {
      let res = {};
      if (this.name && this.isSearch) {
        res = await selectInternalRoleUser({
          code: this.code,
          ...this.page,
          employeeName: this.name,
        });
      } else {
        res = await selectInternalRoleUser({ code: this.code, ...this.page });
      }
      if (res.code === 200) {
        //
        console.log(res.data);
        this.userList = res.data.list;
        this.page.total = res.data.total;
        const $table = this.$refs.xTable1
        $table.loadData(this.userList);
      }
    },
    searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = true;
      this.selectInternalRoleUser();
    },
    resetFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.name = "";
      this.isSearch = false;
      this.selectInternalRoleUser();
    },
    async getRoleList() {
      const res = await getDictValueAndNameSource("BUILTIN_ROLE");
      if (res.code === 200) {
        this.roleList = res.data;
        this.isActive = this.roleList["0"];
        console.log(this.isActive);
        console.log(this.roleList);
      }
    },
    async getDeptListEasy() {
      const res = await getDeptListEasy();
      if (res.code === 200) {
        this.deptList = res.data;
      }
      console.log(res);
    },
    async selDept(val) {
      console.log(val);
      console.log(this.roleFormData.deptId);
      this.roleFormData.name = "";
      this.nameList = [];
      const res = await selectSysUserByDept({
        code: this.code,
        deptId: this.roleFormData.deptId,
      });
      if (res.code === 200) {
        this.nameList = res.data;
        console.log(this.nameList, "用户");
      }
    },
    addUserFn() {
      this.dialogFormVisible = true;
    },
    async del(row) {
      const res = await deleteInternalRoleUser({ id: row.id });
      if (res.code === 200) {
        this.$message.success("删除成功");
        if (this.userList.length === 1 && this.page.pageNum > 1)
          this.page.pageNum--;
        this.selectInternalRoleUser();
      } else {
        // this.$message.error(res.message);
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.selectInternalRoleUser();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      this.selectInternalRoleUser();
    },
    btnClose() {
      this.roleFormData.name = "";
      this.roleFormData.deptId = "";
      this.$refs.addForm.resetFields();
      this.dialogFormVisible = false;
    },
    async btnOk() {
      this.$refs.addForm.validate(async (isOk) => {
        if (isOk) {
          // 添加
          console.log(this.code, "111");
          const res = await bindRoleUser({
            userId: this.roleFormData.name,
            code: this.code,
          });
          // console.log(this.code)
          if (res.code === 200) {
            this.$message.success(res.message);
            // this.dialogFormVisible = false
            this.btnClose();
            this.selectInternalRoleUser();
            // this.get
          } else {
            // this.$message.error(res.message);
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.inner {
  display: flex;
  height: 100%;

  .left {
    width: 304px;
    padding: 32px;
    height: 100%;
    border-right: 1px solid #e7e7e7;

    .tree {
      width: 240px;
      height: 100%;
      margin: 0;
      padding: 0;
      padding-top: 20px;
      overflow-y: auto;

      .liStyle {
        padding: 0 20px;
        cursor: pointer;
        list-style-type: none;
        height: 45px;
        line-height: 45px;
        text-align: center;
        font-size: 20px;
        font-weight: 700;
      }

      .active {
        background-color: #0052d9;
        color: #fff;
      }
    }
  }

  .right {
    padding: 32px;
    height: 100%;
    // width: 100%;
    flex: 1;
    width: 300px;
    display: flex;
    flex-direction: column;

    .bottomTable {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
  }
}
</style>
